package com.pay.service.impl;

import com.google.common.cache.Cache;
import com.pay.common.utils.RedisUtil;
import com.pay.domain.req.WeixinQrCodeReq;
import com.pay.domain.res.WeixinQrCodeRes;
import com.pay.domain.res.WeixinTokenRes;
import com.pay.domain.vo.WeixinTemplateMessageVO;
import com.pay.service.ILoginService;
import com.pay.service.weixin.IWeixinApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import retrofit2.Call;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ZhouYihe 1552951165@qq.com
 * @create 2024/10/23 15:20
 * @description 微信服务的实现类
 */
@Slf4j
@Service
public class WeixinLoginServiceImpl implements ILoginService {
    @Value("${weixin.config.app-id}")
    private String appid;
    @Value("${weixin.config.app-secret}")
    private String appSecret;
    @Value("${weixin.config.template_id}")
    private String template_id;
    
    @Resource
    private Cache<String, String> weixinAccessToken;
    @Resource
    private IWeixinApiService weixinApiService;
    @Resource
    private Cache<String, String> openidToken;
    // @Resource
    // private RedisUtil redisUtil;
    
    @Override
    public String createQrCodeTicket() throws Exception {
        // 1. 获取 accessToken
        
        // 使用Redis的方式
        // String accessToken = redisUtil.get(appid);
        // if (null == accessToken) {
        //     log.info("Redis中不存在该token,调用方法获取token");
        //     Call<WeixinTokenRes> call = weixinApiService.getToken("client_credential", appid, appSecret);
        //     WeixinTokenRes weixinTokenRes = call.execute().body();
        //     assert weixinTokenRes != null;
        //     accessToken = weixinTokenRes.getAccess_token();
        //     log.info("将token缓存进Redis中:{}", accessToken);
        //     boolean set = redisUtil.set(appid, accessToken);
        //     if (!set) {
        //         log.error("tocken缓存失败:appid:{},token:{}", appid, accessToken);
        //     }
        // }
        
        // 使用本地缓存的方式
        String accessToken = weixinAccessToken.getIfPresent(appid);
        if (null == accessToken) {
            Call<WeixinTokenRes> call = weixinApiService.getToken("client_credential", appid, appSecret);
            WeixinTokenRes weixinTokenRes = call.execute().body();
            assert weixinTokenRes != null;
            accessToken = weixinTokenRes.getAccess_token();
            weixinAccessToken.put(appid, accessToken);
        }
        
        // 2. 生成ticket
        WeixinQrCodeReq weixinQrCodeReq = WeixinQrCodeReq.builder()
                .expire_seconds(2592000)    // 30天
                .action_name(WeixinQrCodeReq.ActionNameTypeVO.QR_SCENE.getCode())
                .action_info(WeixinQrCodeReq.ActionInfo.builder()
                        .scene(WeixinQrCodeReq.ActionInfo.Scene.builder()
                                .scene_id(100601)
                                .build())
                        .build())
                .build();
        
        Call<WeixinQrCodeRes> call = weixinApiService.createQrCode(accessToken, weixinQrCodeReq);
        WeixinQrCodeRes weixinQrCodeRes = call.execute().body();
        assert null != weixinQrCodeRes;
        return weixinQrCodeRes.getTicket();
    }
    
    @Override
    public String checkLogin(String ticket) {
        return openidToken.getIfPresent(ticket);
    }
    
    @Override
    public void saveLoginState(String ticket, String openid) throws IOException {
        openidToken.put(ticket, openid);
        
        // 1. 获取 accessToken 【实际业务场景，按需处理下异常】
        String accessToken = weixinAccessToken.getIfPresent(appid);
        if (null == accessToken){
            Call<WeixinTokenRes> call = weixinApiService.getToken("client_credential", appid, appSecret);
            WeixinTokenRes weixinTokenRes = call.execute().body();
            assert weixinTokenRes != null;
            accessToken = weixinTokenRes.getAccess_token();
            weixinAccessToken.put(appid, accessToken);
        }
        
        // 2. 发送模板消息
        Map<String, Map<String, String>> data = new HashMap<>();
        WeixinTemplateMessageVO.put(data, WeixinTemplateMessageVO.TemplateKey.USER, openid);
        
        WeixinTemplateMessageVO templateMessageDTO = new WeixinTemplateMessageVO(openid, template_id);
        templateMessageDTO.setUrl("https://gaga.plus");
        templateMessageDTO.setData(data);
        
        Call<Void> call = weixinApiService.sendMessage(accessToken, templateMessageDTO);
        call.execute();
    }
}
